module(...,package.seeall)
local math = require "math"
local string = require "string"



local function hex(s)
	 s=string.gsub(s,"(.)",function (x) return string.format("%02X",string.byte(x)) end)
	 return s
end


function readFile(path)
    local file = io.open(path, "rb")
    if file then
        local content = file:read("*all")
        io.close(file)
        return content
    end
    return nil
end


function writeFile(path, fileData)
	io.writefile(path, fileData)
end



function removeFile(path)
    --CCLuaLog("removeFile: "..path)
    io.writefile(path, "")
    if device.platform == "windows" then
        --os.execute("del " .. string.gsub(path, '/', '\\'))
    else
        os.execute("rm " .. path)
    end
end


function checkFile(fileName, cryptoCode)
    cclog("fileName=%s", fileName)
    cclog("remote file cryptoCode=%s", cryptoCode)

    local data=readFile(fileName)
    if data==nil then
        return false
    end

    if cryptoCode==nil then
        return true
    end

    local ms = crypto.md5(hex(data))
    cclog("local  file cryptoCode=%s", ms)
    if ms==cryptoCode then
    	cclog("md5 code is same, do not download...")
        return true
    end

    return false
end

function checkDirOK( path )
	-- cclog("checkDirOK(), path="..path)
    require "lfs"
    local oldpath = lfs.currentdir()
--    CCLuaLog("old path------> "..oldpath)

     if lfs.chdir(path) then
        lfs.chdir(oldpath)
--        CCLuaLog("path check OK------> "..path)
        return true
     end

     if lfs.mkdir(path) then
        CCLuaLog("path create OK------> "..path)
        return true
     end
end


